using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.OData;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
[Authorize]
public class SecurityController : ODataController
{
    private SampleContext _db;


    public Admin Authenticate(string number, string password)
    {
        
        var admin = _db.Admins.SingleOrDefault(x => x.Number == number && x.Password == password);

        // return null if user not found
        if (admin == null)
            return null;

        // authentication successful so generate jwt token
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes("aaaaaaaaaabbbbbbbbb");
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new Claim[]
            {
                    new Claim(ClaimTypes.Name, admin.AdminId.ToString())
            }),
            Expires = DateTime.UtcNow.AddDays(7),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
        };

        var token = tokenHandler.CreateToken(tokenDescriptor);
        admin.Token = tokenHandler.WriteToken(token);

        // remove password before returning
        admin.Password = null;

        return admin;
    }
    public SecurityController(SampleContext context)
    {
        _db = context;
    }
    [AllowAnonymous]
    [HttpGet("/api/login")]
    public IActionResult Login(string number, string password)
    {
        var a = Request;
        var user = Authenticate(number, password);
        if (user == null)
            return BadRequest("Username or password is incorrect");
        else
            return Ok(user);
    }
    [EnableQuery]
    public IActionResult Get()
    {
        return Ok(_db.Users);
    }
    //

    //
}
